package com.yy.tech.inte.service;

import com.yy.tech.inte.service.initializer.HttpRequestInitializerFactory;
import com.yy.tech.inte.service.wrapper.HttpRequestWrapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;

/**
 * technical-identification$
 *
 * @author YY
 * @version 1.0.0
 * @date $ $
 * @description: TODO
 */
public abstract class AbstractInteService {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Environment env;
    @Autowired
    private HttpRequestInitializerFactory initializerFactory;

    protected <T, S> T exchange(final HttpRequestWrapper<T, S> wrapper) {
        long offsetTime = System.currentTimeMillis();
        initializerFactory.initialize(wrapper);
        HttpEntity<S> entity = wrapper.getHttpEntity();
        RestTemplate restTemplate = getRestTemplate();
        logWrite(wrapper,entity,true,offsetTime);
        ResponseEntity<T> responseEntity=restTemplate.exchange(wrapper.getRequestUrl(),wrapper.getMethod(),entity,wrapper.getResponseClass(),wrapper.getUriVariables());
        if(null !=responseEntity){
            logWrite(wrapper,responseEntity,false,offsetTime);
            if (responseEntity.getStatusCode() == HttpStatus.OK && responseEntity.hasBody()){
                return responseEntity.getBody();
            }
        }else {
            logger.warn(">> No response!");
        }
        return null;
    }

    protected<T,S> void logWrite(HttpRequestWrapper<T,S> wrapper,Object entity,boolean request,long offsetTime){
        String type= request?"Request":"Response";
        String json = toJson(entity);
        long time= System.currentTimeMillis()-offsetTime;
        if (wrapper.isLogging() & logger.isInfoEnabled()){
            logger.info(">>[{}] URL[{}] Time[{}] Content[{}].",type,wrapper.getRequestUrl(),time,json);
        }else {
            logger.trace(">>[{}] URL[{}] Time[{}] Content[{}].",type,wrapper.getRequestUrl(),time,json);
        }
    }

    protected String toJson(Object obj){
        return null;
    }

    protected RestTemplate getRestTemplate(){
        return initializerFactory.getRestTemplate();
    }
}
